package com.objectcarpentry.kaylee.ui.handlers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.edit.command.AddCommand;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import com.objectcarpentry.kaylee.KayleeFactory;
import com.objectcarpentry.kaylee.KayleePlugin;
import com.objectcarpentry.kaylee.Library;
import com.objectcarpentry.kaylee.Track;
import com.objectcarpentry.kaylee.gstreamer.jobs.MetadataJob;

public class AddFilesHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String[] filterExtensions = {"*.mp3"};
		Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
		FileDialog fileDialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI);
		fileDialog.setText("Select files to add");
		fileDialog.setFilterPath(System.getProperty("user.home"));
		fileDialog.setFilterExtensions(filterExtensions);
		if (fileDialog.open() != null){
			String[] filenames = fileDialog.getFileNames();
			URI base = URI.createFileURI(fileDialog.getFilterPath());
			
		
			KayleePlugin core = KayleePlugin.getDefault();
			
			final Library library = core.getLibrary();
			final Collection<Track> tracks = new ArrayList<Track>();
			
			for (String f : filenames){
				Track t = KayleeFactory.eINSTANCE.createTrack();
				t.setLocation(base.appendSegment(URI.encodeSegment(f, false)));
				tracks.add(t);
			}
			
			MetadataJob job = new MetadataJob("Metadata tatata", tracks);
			job.addJobChangeListener(new JobChangeAdapter(){
				@Override
				public void done(IJobChangeEvent event) {
					PlatformUI.getWorkbench().getDisplay().asyncExec(
						new Runnable(){
							public void run(){
								KayleePlugin core = KayleePlugin.getDefault();
								Command c = AddCommand.create(core.getEditingDomain(), library, null, tracks);
								core.getEditingDomain().getCommandStack().execute(c);
								try {
									library.eResource().save(Collections.EMPTY_MAP);
								} catch (IOException e){
									e.printStackTrace();
								}
							}
						}
					);
				}
			});
			
			PlatformUI.getWorkbench().getProgressService().showInDialog(null, job);
			job.schedule();
			
		}
		return null;
	}
	
}
